package com.kuzlak.cms.module.wms.controller;

import cn.hutool.core.bean.BeanUtil;
import com.kuzlak.cms.bean.Result;
import com.kuzlak.cms.config.ConstantHeader;
import com.kuzlak.cms.module.sys.entity.SysLoginLog;
import com.kuzlak.cms.module.wms.bean.InBoundVO;
import com.kuzlak.cms.module.wms.bean.MasterVO;
import com.kuzlak.cms.module.wms.entity.WmsBound;
import com.kuzlak.cms.module.wms.entity.WmsInBound;
import com.kuzlak.cms.module.wms.entity.WmsMaster;
import com.kuzlak.cms.module.wms.service.WmsBoundService;
import com.kuzlak.cms.module.wms.service.WmsInBoundService;
import com.kuzlak.cms.module.wms.service.WmsMasterService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Tag(name = "入口管理")
@RestController
@RequestMapping("wms/inbound")
public class InBoundController {
    @Autowired
    private WmsMasterService wmsMasterService;

    @Autowired
    private WmsInBoundService inBoundService;
    @Autowired
    private WmsBoundService boundService;

    @Operation(summary = "入库待审核列表")
    @PostMapping("add")
    public Result add(@RequestBody MasterVO data) {
        SysLoginLog adminToken = ConstantHeader.getAdminToken();
        WmsMaster master = BeanUtil.copyProperties(data, WmsMaster.class);
        master.setOperatorId(adminToken.getUserId());
        boolean save = wmsMasterService.save(master);
        if (save) {
            List<WmsInBound> addInBounds = new ArrayList<>();
            List<InBoundVO> inBounds = data.getInBounds();
            for (InBoundVO inBound : inBounds) {
                WmsBound wmsBound = boundService.findByShopIdAndInfoId(inBound.getShopInfoId(), master.getInfoId());
                WmsInBound bound = BeanUtil.copyProperties(inBound, WmsInBound.class);
                bound.setMasterId(master.getId());
                bound.setInfoId(master.getInfoId());
                bound.setOperatorId(adminToken.getUserId());
                bound.setBoundId(wmsBound.getId());
                addInBounds.add(bound);
            }
            boolean b = inBoundService.saveBatch(addInBounds);
            if (b) {
                return Result.ok("入库成功");
            } else {
                return Result.failure("入库失败");
            }

        } else {
            return Result.failure("入库失败");
        }

    }
}
